
/**
@author: 王猛
@date: 2021-01-11
@Email：837821237@qq.com
*/
import React , {useState,useEffect} from "react"
import './index.css';
import img1 from './img/allian-button.png';
import img2 from './img/allian_1.png';
import img3 from './img/allian_2.png';
import img4 from './img/allian_3.png';
import { Carousel, WingBlank , Modal, Toast, InputItem, Button ,Checkbox, List} from 'antd-mobile';
import {sendMessage, miniLogin ,accountList, setMyAccount} from '../../../server/api'; 
import baseUrl from '../../../server/uploadUrl'
import { useHistory } from 'react-router-dom';


const AgreeItem = Checkbox.AgreeItem;
const CheckboxItem = Checkbox.CheckboxItem;

function closest(el, selector) {
    const matchesSelector = el.matches || el.webkitMatchesSelector || el.mozMatchesSelector || el.msMatchesSelector;
    while (el) {
      if (matchesSelector.call(el, selector)) {
        return el;
      }
      el = el.parentElement;
    }
    return null;
  }
function InviteAlliance() {

    let history = useHistory();

    const [data, setData] = useState([img2,img4,img3]);
    const [imgHeight, setImgHeight] = useState(176);
    const [loginModel, setLoginModel] = useState(false);
    const [phoneError, setPhoneError] = useState(false);
    const [phoneNumber, setPhoneNumber] = useState(null);
    const [verify, setVerify] = useState('');
    const [code, setCode] = useState('');
    const [isChecked, setIsChecked] = useState(false);
    const [accountModel, setAccountModel] = useState(false);
    const [verifyAddress, setVerifyAddress] = useState('/captcha.jpg');


    const [selectIndex, setSelectIndex] = useState(0);
    const [Accountdata, setAccountdata] = useState([]);

    const [vCode, setVerifyCode] = useState(null);

    
    useEffect(() => {

    }, []);
  const onWrapTouchStart = (e) => {
        // fix touch to scroll background page on iOS
        if (!/iPhone|iPod|iPad/i.test(navigator.userAgent)) {
          return;
        }
        const pNode = closest(e.target, '.am-modal-content');
        if (!pNode) {
          e.preventDefault();
        }
      }
     //手机号值改变   
     const onPhoneChange = (value) => {
        if (value.replace(/\s/g, '').length === 11) {
            setPhoneError(true);
        } else {
            setPhoneError(false);
        }
        setPhoneNumber(value);
      }
      //验证码改变
      const onVerifyChange = (value) => {
        console.log('验证码',value)
        setVerify(value);
      }
      //六位数值改变
      const onCodeChange = (value) => {
        setCode(value);
      }
      //获取验证码
     const getCode = async () => {
         console.log(phoneNumber,phoneError,verify);
         if(!phoneNumber){
            Toast.info('请输入手机号');
            return
         }
         if(!phoneError){
             Toast.info('请输入正确手机号');
             return
         }
         
         if(!verify){
            Toast.info('请输入图形验证码');
            return
         }
         let params = {
            telephoneNumber:phoneNumber.replace(/\s/g, ''),
            captcha:verify
         };
         sendMessage(params).then(res=>{
           console.log(res);
           if (res.data.ret) {
             Toast.success('获取验证码成功')
             return 
           }
           Toast.info(res.data.errmsg);
         })
      
        
        
     }
     //加入联盟
    const joinAllian =   () => {
        if(!phoneNumber){
            Toast.info('请输入手机号');
            return
         }
         if(!phoneError){
             Toast.info('请输入正确手机号');
             return
         }
         if(!code){
            Toast.info('请输入验证码');
            return
         }
         if(code.length < 6){
            Toast.info('请输入正确的验证码');
            return
         }  
         if(!isChecked){
            Toast.info('请同意用户服务协议');
            return
         }
         let params = {
          phoneNumber:phoneNumber.replace(/\s/g, ''),
          message:code
         };
         miniLogin(params).then(res=>{
           console.log(res);
           if(res&&res.data.ret){
             let userInfo = JSON.stringify(res.data.data.userInfo);  
             sessionStorage["userInfo"] = userInfo; 
             sessionStorage["token"] = res.data.data.userInfo.token;
             if(res.data.data.type === "old"){
              setLoginModel(false);
              setAccountModel(true);
              getAccountList();
              return
             }
             history.push('/h5-company-allian');
             return
           }
           if(res){
            Toast.info(res.data.errmsg);
           } 
         })
    }
    const changeAggree = (e) => {
          setIsChecked(e.target.checked);
    }
    //账号列表
    const getAccountList = () => {

      accountList().then(res=>{
         console.log(res,'账号列表');
         if(res&&res.data.ret){
           setAccountdata(res.data.data);
           
         }
      })
    }
   //账号值改变 
   const onAccountChange = (i)=>{
    Accountdata.map((item,index)=>{
      if(i===index){
        Accountdata[index].selected = true;
        return
      }
      Accountdata[index].selected = false;
    })
    setSelectIndex(i);
    setAccountdata([...Accountdata]);
   }
   //选择账号
   const selectAccount = ()=>{
      let params = {};
      params.userInfoId = Accountdata[selectIndex].userInfoId;
      params.orgInfoId = Accountdata[selectIndex].orgInfoId;
      setMyAccount(params).then(res=>{
        if(res&&res.data.ret){
          Toast.info('登录成功')
          history.push('/h5-company-allian');
        }
      })
   }
   //刷新验证码
   const refreshVerify = ()=>{
     let address = '/captcha.jpg?' + Math.random();
     setVerifyAddress(address);
   }
    return (
        <div className='invite-alliance-box'>
            <div className='invite-content'>
                <WingBlank>
                    <Carousel
                        autoplay={false}
                        infinite
                        dotStyle={{width:'8px',height:'8px',backgroundColor:'transparent',border:'1px solid rgba(255, 255, 255, 1)',borderRadius:'0',transform:'rotate(45deg)',marginRight:'8px'}}
                        dotActiveStyle={{width:'8px',height:'8px',backgroundColor:'rgba(255, 255, 255, 1)',border:'1px solid rgba(255, 255, 255, 1)',borderRadius:'0',transform:'rotate(45deg)',marginRight:'8px'}}
                    >
                        {data.map((val,index) => (
                                <div key={index} style={{ width: '100%', height: imgHeight ,paddingBottom:'30px'}}>
                                    <img
                                        src={val}
                                        alt=""
                                        style={{ width: '100%', verticalAlign: 'top' }}
                                        onLoad={() => {
                                            // fire window resize event to change height
                                            window.dispatchEvent(new Event('resize'));
                                            setImgHeight('auto' );
                                        }}
                                    />
                                </div>

                        ))}
                    </Carousel>
                </WingBlank>
            </div>
                <div className='invite-button' >
                    <img onClick={()=>setLoginModel(true)} src={img1} alt='' />
                </div>
                <Modal
          visible={loginModel}
          className="login-model"
          transparent
          maskClosable={false}
          onClose={()=>setLoginModel(false)}
          title="加入联盟"
          wrapProps={{ onTouchStart: onWrapTouchStart }}
        >
          <div className="login-form">
          <InputItem
            type="phone"
            placeholder="手机号"
            onChange={onPhoneChange}
            value={phoneNumber}
          ></InputItem>
          <div className="verify-warp">
          <InputItem
            type="text"
            placeholder="图形验证码"
            onChange={onVerifyChange}
            value={verify}
          ></InputItem> 
          <img onClick={()=>refreshVerify()}  className="verify-content" src={ baseUrl.uploadUrl + verifyAddress}></img>   
          </div>
          
          <div className="code-warp">
          <div>

          </div>
          <InputItem
            type="number"
            maxLength="6"
            placeholder="6位验证码"
            onChange={onCodeChange}
            value={code}
          ></InputItem>
          <div className="code-text" onClick={()=>getCode()}>
             获取验证码
          </div>
          </div>         
          <AgreeItem data-seed="logId" onChange={(e) => changeAggree(e)}>
             <span onClick={()=>history.push('/h5-agreement-content')} className="aggrement-text">同意《会员服务协议》</span>      
          </AgreeItem>
           <Button type="primary" onClick={()=>joinAllian()}>确认</Button>
          </div>
        </Modal>

        <Modal
          visible={accountModel}
          className="login-model"
          transparent
          maskClosable={false}
          onClose={()=>setLoginModel(false)}
          title="加入联盟"
          wrapProps={{ onTouchStart: onWrapTouchStart }}
        >
          <div className="account-list">
              <div>
              <List >
        {Accountdata.map((i,c) => (
          <CheckboxItem key={c} checked={i.selected} onChange={() => onAccountChange(c)}>
            <div className="account-warp">
              <div className="account-lfet">
                 <div className="account-name">
                    {i.companyName}
                 </div>
                 <div className="account-phone">
                   {phoneNumber.replace(/\s/g, '')}
                 </div>
              </div>
             {
                i.accountType===1?(
                <div className="account-label-1">
                   个人
                </div>
                ):null
             } 
             {
                i.accountType===2?(
                <div className="account-label-2">
                   机构
                </div>
                ):null
             } 
             {
                i.accountType===3?(
                <div className="account-label-1">
                   子账号
                </div>
                ):null
             } 
            </div>
          </CheckboxItem>
        ))}
         </List>
              </div>
          </div>
          <div className="login-form">
           <Button onClick={()=>selectAccount()} type="primary" >确认</Button>
          </div>
        </Modal>
        </div>
        
    )
    
}
export default InviteAlliance;

